<!-- 账号登录输入框 -->
<template>
  <div class="login_account">
    <!-- form -->
    <el-form :model="accountForm" ref="formRef" :rules="rules" label-width="80px">
      <!-- account -->
      <el-form-item label="账号:" prop="account">
        <el-input v-model.trim="account" clearable placeholder="2-10位数字或字母" @input="handleInput" />
      </el-form-item>
      <!-- password -->
      <el-form-item label="密码:" prop="password">
        <el-input v-model.trim="password" type="password" show-password placeholder="3-9位数字或字母" />
      </el-form-item>
    </el-form>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, toRefs } from 'vue'
import { useStore } from 'vuex'
import { rules } from '../config/account.config'
import { ElForm } from 'element-plus'
import { LStorage } from "@/utils/cache"
import { CACHE_LOGIN_USER_INFO } from "@/store/const"
const store = useStore()

const accountForm = reactive({
  account: 'admin',
  password: '123456'
})

const init = (val: string) => {
  const cache = LStorage.get(val)
  // 匹配成功就显示缓存的信息，不成功就显示输入的信息
  if (cache != '') {
    let { account, password } = cache
    accountForm.account = account
    accountForm.password = password
  }
}
// 键盘输入事件
const handleInput = (val: string) => {
  // 调用本地缓存信息
  init(val)
}

const { account, password } = toRefs(accountForm)
const formRef = ref<InstanceType<typeof ElForm>>()
// 提交
const loginAction = (isRemPwd: boolean) => {
  if (!formRef.value) return
  formRef.value?.validate((valid) => {
    if (!valid) return
    // 记住密码--本地缓存
    if (isRemPwd) {
      LStorage.set(CACHE_LOGIN_USER_INFO, {
        account: account.value,
        password: password.value,
      }, 1000)
    } else {
      // 清除之前记住的当前密码
      LStorage.remove(account.value)
    }
    // 动用登录接口
    store.dispatch('login/loginAccountAction', { username: accountForm.account, password: accountForm.password })
    resetForm()
  })
}
// 重置
const resetForm = () => {
  if (!formRef.value) return
  formRef.value?.resetFields()
}

defineExpose({
  loginAction,
  resetForm
})
</script>
<style lang="less" scoped>
</style>
